/**
 * Created by syz on 2016/1/13.
 */

'use strict';

var dbDao = require('../../../models/dbBase.js');
var smsclient = require('./smsClient.js');

var moment = require('moment');
var templateId = '181234';

var sendSMS= function(mobile,pin,cb) {
  //通过短信平台发送短息到手机
  smsclient.sendTemplateSms(mobile, [pin, '1'], templateId, function(err, res){
    if (err) {
      return cb(err);
    }
    if (res.statusCode != '000000') {
      cb(new Error(res.statusMsg));
    } else {
      cb(null, res);
    }
  });
}
var getPin=function() {
  var chars = "0123456789";
  var stringLength = 6;

  var randomString = '';
  for (var i = 0; i < stringLength; i++) {
    var rnum = Math.floor(Math.random() * chars.length);
    randomString += chars.substring(rnum, rnum + 1);
  }
  return randomString;
}
var updateMobilePin=function(phone,pin,cb) {
  var sql = "delete from smsPinVerify where phone=?";
  var params = [phone];
  dbDao.querys(sql, params, function (err, result) {
    if (err) {
      cb('error');
    } else {
      var pinsql = "insert into smsPinVerify(phone,pin,created) values(?,?,?)";
      var params = [phone, pin, moment().unix()];
      dbDao.querys(pinsql, params, function (err, result) {
        if (result.resultCode == '0') {
          cb(null);
        } else {
          cb('err')
        }
      });
    }
  });
}
var insertMobilePin=function(phone,pin,cb) {
  var pinsql = "insert into smsPinVerify(phone,pin,created) values(?,?,?)";
  var params = [phone, pin, moment().unix()];
  dbDao.querys(pinsql, params, function (err, result) {
    if (err) {
      cb('err')
    } else {
      cb(null);
    }
  });
}

var sendPin = function (mobile, cb) {
    var sql = "select * from smsPinVerify where phone='" + mobile + "'";
    var pin=getPin();
    dbDao.find(sql, function (err, result) {
      if (err) {
      } else {
        if (result.length > 0) {
          updateMobilePin(mobile,pin,function(err) {
            if (err) {
              cb(err);
            } else {
              sendSMS(mobile, pin, function (err) {
                if (err) {
                  cb(err)
                } else {
                  cb(null);
                }
              })
            }
          })
        }else {
          insertMobilePin(mobile,pin,function(err){
            if(err){
              cb(err);
            }else{
              sendSMS(mobile,pin,function(err){
                if(err){
                  cb(err)
                }else{
                  cb(null);
                }
              })
            }
          })
        }
      }
    });
}

module.exports = sendPin;
